package com.dbh.jdk.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 *  信号量器示例
 *
 * @author dongbanghui
 * @date 2018/06/02
 */
public class SemaphoreDemo implements Runnable {

	final Semaphore semp = new Semaphore(5);
	
	@Override
	public void run() {
		try {
			//获取一个准入许可
			semp.acquire();
			//模拟耗时操作
			Thread.sleep(2000);
			System.out.println(Thread.currentThread().getId() + ":done!");
			//释放一个准入许可
			semp.release();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public static void main(String[] args) {
		ExecutorService exec = Executors.newFixedThreadPool(10);
		SemaphoreDemo demo = new SemaphoreDemo();
		for(int i=0;i<20;i++) {
			exec.submit(demo);
		}
	}
}
